﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using PessMvc.Helpers;
using System.Web.Security;
using System.Security.Principal;
using System.Configuration;
using PessModel;

namespace PessMvc.Models
{
    public class ExpertJudgeInfoComplete : AuthorizeAttribute 
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //        return RedirectToAction("Edit", "ExpertJudge", new { serialNumber = model.UserName, returnUrl = returnUrl });
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    {"action","Logon"},
                    {"controller","Account"}                    
                });
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (System.Web.Security.Roles.IsUserInRole("ExpertJudge"))
            {
                return Utility.IsExpertJudgeInfoComplete(Membership.GetUser().UserName);
            }
                
            return base.AuthorizeCore(httpContext);
        }
    }

    public class RedirectToAuthor : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //        return RedirectToAction("Edit", "ExpertJudge", new { serialNumber = model.UserName, returnUrl = returnUrl });
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    {"action","Proposals"},
                    {"controller","Author"}                    
                });
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!System.Web.Security.Roles.IsUserInRole("Author"))
            {
                return true;
            }

            return false;//base.AuthorizeCore(httpContext);
        }
    }

    public class NotNeedToChangePassword : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //        return RedirectToAction("Edit", "ExpertJudge", new { serialNumber = model.UserName, returnUrl = returnUrl });
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    {"action","ChangePassword"},
                    {"controller","Account"}                    
                });
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (Membership.GetUser() == null)
                return true;
            return Utility.NotNeedChangePassword(Membership.GetUser().UserName);//base.AuthorizeCore(httpContext);
        }
    }

    public class ArchiveSubmssionAllowed : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //base.HandleUnauthorizedRequest(filterContext);
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    {"action","Logon"},
                    {"controller","Account"}                    
                });
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            int activitId=int.Parse(ConfigurationManager.AppSettings["CurrentActivityID"]);
            Activity activity;
            using (PESSEntities db=new PESSEntities()){
                activity=db.Activities.Find(activitId);
            }
            return Utility.IsArchiveModificationAllowed(activity, new ModelStateDictionary());
        }
    }

    /// <summary>
    /// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
    /// around a cookie/session bug in Flash. 
    /// </summary>
    /// <remarks>
    /// Details of the bug and workaround can be found on this blog:
    /// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
    /// </remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class TokenizedAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The key to the authentication token that should be submitted somewhere in the request.
        /// </summary>
        private const string TOKEN_KEY = "authCookie";

        /// <summary>
        /// This changes the behavior of AuthorizeCore so that it will only authorize
        /// users if a valid token is submitted with the request.
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string token = httpContext.Request.Params[TOKEN_KEY];

            if (token != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

                if (ticket != null)
                {
                    var identity = new FormsIdentity(ticket);
                    string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
                    var principal = new GenericPrincipal(identity, roles);
                    httpContext.User = principal;
                }
            }

            return base.AuthorizeCore(httpContext);
        }
    }


}